// 引入web3.js库
let Web3 = require("web3")

// 创建web3.js实例，地址对应的是Gannache以太坊测试网
var web3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:7545"))
// 获取ABI接口文件并转为json格式
var contractAbi = JSON.parse('[{"constant":true,"inputs":[],"name":"getNum","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_num","type":"uint256"}],"name":"setNum","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]')
// 获取合约地址
var contractAddress = "0x22F24C10D38Db572e833Ec5dcA20FE8C6cd07210"

// 创建合约对象
var simpleContract = new web3.eth.Contract(contractAbi,contractAddress)

// 重要：web3.js库调用智能合约读/写函数都是采用异步的方式，不会按照代码执行顺序返回结果，而是
// 按照函数的执行速度确定返回结果的先后


// 调用合约（setNum是合约的写函数，涉及交易）
simpleContract.methods.setNum(100)
.send({from:"0xdc913Dc03d9Eb7AEc929B1389C88fa3BCd4D3CeF",gas:150000,gasPrice:'100000'})
.on('receipt',function(receipt){
    console.log(receipt);
//     // 调用合约（读函数）//这是套娃，解决异步处理问题
// simpleContract.methods.getNum().call(function(error,result){
//     console.log(result);
// })
})
 // 调用合约（读函数）
 simpleContract.methods.getNum().call(function(error,result){
    console.log(result);
})

